// src/service/base.ts
import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { pickBy } from 'lodash';
@Provide()
export abstract class BaseService<T> {
  public abstract entity: Repository<T>;
  add(query) {
    return this.entity.insert(query);
  }
  upsert(query, options?) {
    return this.entity.upsert(query, {
      ...options,
    });
  }
  update(query) {
    return this.entity.update(query.id, query);
  }
  delete(ids: number | string | string[]) {
    return this.entity.delete(ids);
  }
  info(data) {
    return this.entity.findOne({ where: data });
  }
  async page({ data, otherData = {} }) {
    const { page = 1, size = 10, ...params } = data || {};

    const [list, total] = await this.entity.findAndCount({
      where: pickBy(params),
      take: size,
      skip: (page - 1) * size,
      ...otherData,
    });
    return { list, pagination: { total, size, page } };
  }
  list({ data = {}, orderData = {}, otherData = {} }) {
    return this.entity.find({
      where: pickBy(data),
      order: { ...orderData },
      ...otherData,
    } as any);
  }
}
